package com.example.demo1.service;

import com.example.demo1.exception.ExceptionEnum;
import com.example.demo1.exception.ToprsException;
import com.example.demo1.maper.UserMapper;
import com.example.demo1.model.User;
import com.example.demo1.util.md5Util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

@Service
@Repository
public class UserService {

    @Autowired
    UserMapper uMapper;

    public User getUserByid(Integer id) {
        return uMapper.getUserById(id);
    }

    public void register(String userName, String passWord) throws ToprsException {

        User result = uMapper.getUserByUserName(userName);
        if (result != null) {
            throw new ToprsException(ExceptionEnum.USER_EXTI);
        }
        try {
            passWord = md5Util.getMD5String(passWord);
        } catch (Exception e) {
            e.printStackTrace();
        }
        int count = uMapper.addUser(userName, passWord);
        if (count < 1) {
            throw new ToprsException(ExceptionEnum.USER_ADD_FAIL);
        }
    }

    public User login(String userName, String passWord) throws Exception {
        try {
            passWord = md5Util.getMD5String(passWord);
        } catch (Exception e) {
            e.printStackTrace();
        }

        User user = uMapper.queryUser(userName, passWord);
        if (user == null) {
            throw new ToprsException(ExceptionEnum.PASS_WORD_ERROR);
        }
        return user;

    }

}
